package com.huyn.baseframework.dynamicload;

import android.widget.ScrollView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huyaonan on 16/6/16.
 */
public class PositionManageUtil implements IPositionManager {

    private List<IPositionListener> mPositions;

    private List<Integer> mPosList;
    private int mScreenBottom = 0;

    private ScrollView mScrollview;

    public PositionManageUtil(ScrollView view) {
        this.mScrollview = view;
    }

    public void storeListenerPositions(int delay) {
        if(mPositions == null)
            return;
//        if(mPosMaps == null)
//            mPosMaps = new HashMap<>();
        if(mPosList == null)
            mPosList = new ArrayList<>();
        for(IPositionListener listener : mPositions) {
            int[] pos = listener.getLocations();
//            mPosMaps.put(listener, pos);
            mPosList.add(pos[1]);
        }

        mScrollview.postDelayed(new Runnable() {
            @Override
            public void run() {
                listener(0);
            }
        }, delay);
    }

    public void reportItemsPosition() {
        int[] locs = new int[2];
        mScrollview.getLocationOnScreen(locs);
        mScreenBottom = mScrollview.getHeight()+locs[1];
    }

    @Override
    public void add(IPositionListener listener) {
        if(mPositions == null)
            mPositions = new ArrayList<>();
        mPositions.add(listener);
    }

    @Override
    public void remove(IPositionListener listener) {
        if(mPositions == null)
            return;
        mPositions.remove(listener);
    }

    @Override
    public void listener(int scrollY) {
        if (mPosList == null || mPositions == null || mPositions.size() != mPosList.size())
            return;
        synchronized (mPosList) {
            int delay = 300;
            int size = 0;
            List<Integer> toBeRemoveIndex = new ArrayList<>();
            for (int i = 0; i < mPositions.size(); i++) {
                if (mPosList.get(i) < mScreenBottom + scrollY) {
                    mPositions.get(i).notifyAnim(delay * size);
                    size++;
                    toBeRemoveIndex.add(i);
                }
            }

            /*移除已经执行过动画的组件*/
            for(int i=toBeRemoveIndex.size()-1; i>=0; i--) {
                int index = toBeRemoveIndex.get(i).intValue();
                mPositions.remove(index);
                mPosList.remove(index);
            }
        }
    }
}
